# 这个程序要实现的功能：
# 接口1：接收账号和密码，验证，正确就返回cookie，并将这个cookie存在服务器上，服务器设置每天定时删除已经储存的cookie
# 目前未使用数据库，因此计划设置的cookie都用永久的cookie，一但生成则不失效
# 以下所有接口都要先验证cookie是否正确，否则返回未登录页面

# 所有跳转都通过这个接口，先验证一次登录状态，再根据需要重定向到具体网页

import json
import time
import hashlib
from flask import Flask
from flask import request
from flask import make_response
from flask import render_template
user_list=['chenguiying','chenmingshuai','fangkailin','hejie','wuboyi']
time_local = time.localtime(time.time())
date_time = time.strftime("%Y-%m-%d", time_local)
# 这个md5从请求的
def verify(md5):
    f=open(date_time+"Cookie.txt","r")
    cookie_list=f.readlines()
    f.close()
    for cookie in cookie_list:
        cookie.strip("\n")
        if md5==cookie:
            return True
    return False


def buildCookie(username,pwd):

    # print(date_time)
    info_dict={
        "username":username,
        "pwd":pwd,
        "date":date_time
    }
    info=str(info_dict)
    # print(info)
    md=hashlib.md5()
    md.update(info.encode(encoding="utf-8"))
    pwdMD=md.hexdigest()
    f=open(date_time+"Cookie.txt","a")
    f.write(pwdMD+"\n")
    f.close()
    return pwdMD


app=Flask(__name__)
'''
# 用于测试代码的接口
@app.route('/hello')
def hello_world():
    # f = open("templates/index.html", "r", encoding="gbk")
    # str = f.readline()
    # f.close()
    # response = make_response("<html></html>",302)
    # response.headers={
    #     'content-type':'text/plain',
    #     'location':'https://www.baidu.com'
    #     }
    # MyCookie = buildCookie("chenmingshuai", "123456")
    MyCookie="afglgjljafsafs"
    response = make_response("<html></html>",302)
    response.headers = {
        'content-type': 'text/plain',
        'location': 'http://www.baidu.com',  # location里放入登录后要跳转的网页
        'Set-Cookie':"md5="+MyCookie
    }
    f=open("cookie.txt","a")
    f.write(MyCookie)
    f.close()
    return response
'''


# post接收到的数据格式应该为表单form，json格式的  {"loginUserName":username,"pwd":password}
@app.route('/login',methods=['POST'])
def login():
    # ipv4=request.remote_addr
    # print(ipv4)
    username=request.form['loginUserName']
    pwd=request.form['pwd']
    if username=="" or pwd=="":
        return "提交数据格式错误：用户名或密码不能为空"
    else:
        for user in user_list:
            if user==username:
                f=open(username+".txt","r")
                psd=f.readline()
                f.close()
                if psd==pwd:
                    MyCookie=buildCookie(username,pwd)
                    response=make_response("<html></html>",302)
                    response.headers={
                        'content-type': 'text/plain',
                        'location':'http://www.baidu.com',   # location里放入登录后要跳转的网页
                        'Set-Cookie':'md5='+MyCookie
                    }
                    # response.set_cookie("md5",MyCookie)
                    return response
                else:
                    return "用户名或者密码错误"
            else:
                continue
        return "该用户未注册"


# 暂时不开放注册账号
# @app.route("/register")
# def resgister():



if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8080)

